<template>
  <a-modal
    :maskClosable="maskClosable"
    title="编辑策略 "
    :width="1000"
    :model="form"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :labelCol="{span: 3}"
        :wrapperCol="{span: 12}"
      >
        <a-card
          title="基本信息"
          :bordered="false"
        >
          <a-form-model-item
            prop="name"
            label="策略名称"
          >
            <a-input
              autocomplete="off"
              v-model="form.name"
            />
          </a-form-model-item>
        </a-card>
        <a-card
          title="告警规则设置"
          :bordered="false"
        >
          <a-form-model-item :wrapperCol="{span: 23, offset: 1}">
            <a
              style="color: #017972;"
              @click="addRule"
            >
              <a-icon type="plus" />
              添加告警规则
            </a>

            <a-row
              :gutter="[8, 8]"
              type="flex"
              justify="start"
              v-for="(rule, index) in form.ruleVos"
              :key="index"
            >
              <a-col :span="1">
                <label class="ant-form-item-required" />
              </a-col>

              <a-col :span="5">
                <a-form-model-item
                  :prop="'ruleVos.' + index + '.meter'"
                  :rules="[
                    { required: true, message: '请选择监控项', trigger: 'blur' },
                    { validator: meterValidator(index, form.ruleVos) }
                  ]"
                >
                  <a-select
                    :getPopupContainer="
                      triggerNode => {
                        return triggerNode.parentNode || document.body;
                      }"
                    v-model="rule.meter"
                    placeholder="监控项"
                    @change="getMeterUnit(rule)"
                    @blur="onMeterBlur()"
                  >
                    <a-select-option
                      v-for="(d, i) in meterList"
                      :key="'meter_' + i"
                      :value="d.meter"
                    >
                      {{ d.chnName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="3">
                <a-form-model-item
                  :prop="'ruleVos.' + index + '.comparisonOperator'"
                  :rules="[{
                    required: true,
                    message: '请选择比较符',
                    trigger: 'blur'
                  }]"
                >
                  <a-select
                    :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }"
                    placeholder="比较符"
                    v-model="rule.comparisonOperator"
                  >
                    <a-select-option
                      v-for="(value,key) in comparisonOperatorMap"
                      :key="key"
                      :value="parseInt(key)"
                    >
                      {{ value }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="5">
                <a-form-model-item
                  :prop="'ruleVos.' + index + '.threshold'"
                  :rules="[
                    { required: true, message: '请输入阈值' },
                    { validator: validators.xmax({max:999999}), trigger: 'blur', },
                    { validator: validators.xmin({min:0}), trigger: 'blur', },
                  ]"
                >
                  <a-input
                    autocomplete="off"
                    :max-length="9"
                    placeholder="阈值"
                    v-model="rule.threshold"
                    :addon-after="rule.unit"
                    @keyup="clearNoNum(rule)"
                    @blur="clearNoNum(rule)"
                  />
                  <!-- <a-input-number
                    placeholder="阈值"
                    :min="-999999"
                    :max="999999"
                    v-model="rule.threshold"
                  />
                  <div
                    v-if="rule.unit"
                    class="rule-unit"
                  >
                    {{rule.unit}}
                  </div> -->
                </a-form-model-item>
              </a-col>

              <a-col :span="3">
                <a-form-model-item>
                  <p style="text-align: right;"><label class="ant-form-item-required" />持续时间：</p>
                </a-form-model-item>
              </a-col>

              <a-col :span="3">
                <a-form-model-item
                  :prop="'ruleVos.' + index + '.duration'"
                  :rules="[{
                    required: true,
                    message: '请选择持续时间',
                    trigger: 'blur'
                  }]"
                >
                  <a-select
                    :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }"
                    placeholder="时间"
                    v-model="rule.duration"
                  >
                    <a-select-option
                      v-for="(value,key) in durationMap"
                      :key="key"
                      :value="parseInt(key)"
                    >
                      {{ value }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="3">
                <a-form-model-item
                  :prop="'ruleVos.' + index + '.level'"
                  :rules="[{
                    required: true,
                    message: '请选择等级',
                    trigger: 'blur'
                  }]"
                >
                  <a-select
                    :getPopupContainer="
                      triggerNode => {
                        return triggerNode.parentNode || document.body;
                      }"
                    v-model="rule.level"
                    placeholder="等级"
                  >
                    <a-select-option
                      v-for="(value,key) in levelMap"
                      :key="key"
                      :value="parseInt(key)"
                    >
                      {{ value }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="1">
                <a-icon
                  v-if="form.ruleVos.length > 1"
                  type="minus"
                  style="cursor: pointer; line-height: 40px;"
                  @click="delRule(index)"
                />
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-card>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>
<script>
  import { gPostAction } from '@/api/manage'
  import { filterToFloat } from "@/utils/util"

  export default {
    name: 'AddModal',
    data() {
      return {
        visible: false,
        confirmLoading: false,
        policyId: '',
        form: {
          name: '',
          ruleVos: [],
        },
        meterList: [],
        durationMap: {
          60: '1分钟',
          300: '5分钟',
          900: '15分钟',
          1800: '30分钟',
          3600: '60分钟'
        },
        comparisonOperatorMap: {
          0: '>=',
          1: '>',
          2: '<=',
          3: '<',
          4: '=',
          5: '!='
        },
        levelMap: {
          1: '一般',
          2: '重要',
          3: '严重'
        },
        // 校验
        rules: {
          name: [{
              required: true,
              message: '请输入策略名称',
              trigger: 'blur'
            },
            { validator: this.validators.noWhitespace(), },
            { validator: this.validators.noIllegalString() },
            { max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
          ],
          validateFirst: true,
        },
        maskClosable: false,
      }
    },
    methods: {
      clearNoNum(rule) {
        if (rule && rule.threshold) {
          let threshold = filterToFloat(rule.threshold);

          if (rule.unit.indexOf('%') !== -1) {
            if (isNaN(threshold)) {
              threshold = 0;
            } else if (parseFloat(threshold) > 100) {
              threshold = 100;
            }
          } else {
            if (parseFloat(threshold) > 999999) {
              threshold = 999999;
            }
          }

          rule.threshold = threshold;
        }
      },
      meterValidator(index, list) {
        return function (rule, value, callback) {
          let msg = '';
          list.forEach((item, i) => {
            if (item.meter && value && item.meter === value && i !== index) {
              msg = '不能选择重复监控项';
            }
          });
          if (msg) {
            callback(msg);
          } else {
            callback();
          }
        }
      },
      onMeterBlur() {
        let list = this.form.ruleVos;
        list.forEach((item, i) => {
          if (item.meter) {
            this.$refs.ruleForm.validateField('ruleVos.' + i + '.meter');
          }
        });
      },
      update(item) {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
        }
        this.visible = true
        Promise.all([this.loadDetail(item), this.loadMeter()]).then(res => {
          this.initData(res[0].data)
        })
      },
      addRule() {
        this.form.ruleVos.push({
          meter: undefined,
          comparisonOperator: undefined,
          duration: undefined,
          level: undefined,
          threshold: undefined,
        })
      },
      delRule(index) {
        this.form.ruleVos.splice(index, 1)
      },
      loadMeter() {
        return new Promise((resolve, reject) => {
          gPostAction('/statistics/listMeter', {}).then(res => {
            if (res.success) {
              res.data.forEach((item) => {
                if (item.meter && (item.meter.indexOf('air') > -1 || item.meter.indexOf('ups') > -1)) {
                  this.meterList.push(item);
                }
              });
              resolve(res)
            } else {
              reject(res)
            }
          })
        })
      },
      loadDetail(item) {
        if (!item.id) return
        const postData = {
          policyId: item.id,
          title: "精确管控与供电制冷联动-供电制冷最优模型-供电制冷设备告警管理-告警阈值设置",
          content: "查看告警阈值设置"
        }
        return new Promise((resolve, reject) => {
          gPostAction('/policy/detail', postData).then(res => {
            if (res.success) {
              resolve(res)
            } else {
              reject(res)
            }
          })
        })
      },
      getMeterUnit(rule) {
        if (rule.meter) {
          for (const d of this.meterList) {
            if (d.meter === rule.meter) {
              rule.comparisonOperator = undefined
              rule.threshold = undefined
              rule.unit = d.unit
              rule.meterChnName = d.chnName
              return
            }
          }
        }
      },
      initData(item) {
        this.policyId = item.id
        const ruleVos = item.ruleVos
        ruleVos.forEach((rule, index) => {
          if (rule.threshold) {
            rule.threshold = parseFloat(rule.threshold).toFixed(2)
          } else if (rule.threshold === 0) {
            rule.threshold = parseFloat('0').toFixed(2)
          }
          for (const d of this.meterList) {
            if (d.meter === rule.meter) {
              ruleVos[index].unit = d.unit
            }
          }
        })
        this.form = {
          name: item.policyName,
          ruleVos: ruleVos || []
        }
      },
      handleOk(e) {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.confirmLoading = true
            const requestData = {
              policyId: this.policyId,
              policyName: this.form.name,
              enable: 1,
              notifyEnable: false,
              title: "精确管控与供电制冷联动-供电制冷最优模型-供电制冷设备告警管理-告警阈值设置",
              content: "编辑策略"
            }

            this.form.ruleVos.forEach((item, index) => {
              requestData['ruleVos[' + index + '].id'] = item.id
              requestData['ruleVos[' + index + '].comparisonOperator'] = item.comparisonOperator
              requestData['ruleVos[' + index + '].duration'] = item.duration
              requestData['ruleVos[' + index + '].level'] = item.level
              requestData['ruleVos[' + index + '].threshold'] = item.threshold
              requestData['ruleVos[' + index + '].statistics'] = 'avg'
              requestData['ruleVos[' + index + '].enabled'] = 1
              if (item.meter) {
                requestData['ruleVos[' + index + '].meter'] = item.meter
                requestData['ruleVos[' + index + '].meterChnName'] = item.meterChnName
                requestData['ruleVos[' + index + '].resourceType'] = item.meter.substr(0, item.meter.indexOf('.'))
              }
            })
            gPostAction('/policy/update1', requestData)
              .then((res) => {
                if (res.success) {
                  this.$message.success('操作成功')
                  this.$emit('ok')
                }
              })
              .finally(() => {
                this.handleCancel()
              })
          } else {
            return false
          }
        })
      },
      handleCancel() {
        this.confirmLoading = false
        this.visible = false
      },
    },
  }
</script>

<style scoped>
  .rule-box {
    display: flex;
    justify-content: space-between;
  }
</style>